<template>
  <div>
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="服务器地址" size="mini">
        <el-input style="width: 12em" v-model="listQuery.host" placeholder="服务器地址"></el-input>
      </el-form-item>
      <el-form-item size="mini">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetList">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button class="serverAdd" type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="serverAdd" round>新增</el-button>
    <el-table
        v-loading="tableLoading"
        :data="tableData"
        row-key="id"
        style="width: 100%"
        :expand-row-keys="expandRowKeys">
      <el-table-column
          width="120px"
          label="服务器地址"
          prop="host">
      </el-table-column>
      <el-table-column
          width="60px"
          label="端口"
          prop="port">
      </el-table-column>
      <el-table-column
          width="120px"
          label="创建用户"
          prop="createUser">
      </el-table-column>
      <el-table-column
          width="100px"
          label="创建时间"
          prop="createTime">
      </el-table-column>
      <el-table-column
          label="标签">
        <template slot-scope="scope">
          <el-tag
              type="success"
              v-if="scope.row.tags!=null && scope.row.tags != ''"
              v-for="item in (scope.row.tags!=null && scope.row.tags != '' ? scope.row.tags : '').split(',')">{{item}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          width="350px"
          label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="primary"
              @click="serverDetail(scope.$index, scope.row)">详情</el-button>
          <el-button
              size="mini"
              type="info"
              @click="serverUpdate(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="error"
              @click="serverDelete(scope.$index, scope.row)">删除</el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.$index, scope.row)" style="margin-left: 10px" trigger="click">
            <span class="el-dropdown-link">
              功能菜单<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-medal-1" :command="1">主线日志</el-dropdown-item>
              <el-dropdown-item icon="el-icon-position" :command="2">OpenApi日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="40%">
      <el-form :model="addServerInfo" :rules="addServerInfoRules" ref="addServerInfoRules" label-width="100px" class="demo-ruleForm" label-position="left">
        <el-form-item label="服务器地址" prop="host">
          <el-input v-model="addServerInfo.host"></el-input>
        </el-form-item>
        <el-form-item label="服务器端口" prop="port">
          <el-input v-model.number="addServerInfo.port"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addServerInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="服务器密码" prop="password">
          <el-input type="password" v-model="addServerInfo.password"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
              v-model="selectTags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签">
            <el-option
                v-for="item in tagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="addButtonItem">
          <el-button v-if="dialogType == 0" size="small" type="primary" @click="submitAdd('addServerInfoRules')">立即添加</el-button>
          <el-button v-if="dialogType == 1" size="small" type="primary" @click="submitUpdate('addServerInfoRules')">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { ipcRenderer } from 'electron'
export default {
  name: "ServerInfoManage",
  data: function(){
    let checkPort = (rule, value, callback) => {
      if (!value) {
        callback(new Error('服务器端口不能为空'))
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'))
      } else {
        callback()
      }
    }
    return {
      tableLoading: false,
      listQuery: {
        "host": '',
        "pageNo": 1,
        "pageSize": 10
      },
      expandRowKeys: [],
      tableData:[],
      dialogVisible: false,
      addServerInfo: {
        host: '',
        port: null,
        username: null,
        password: null
      },
      addServerInfoRules: {
        host: [
          {required: true, message: '服务器地址不能为空', trigger: 'blur'}
        ],
        port: [
          {required: true, validator: checkPort, trigger: 'blur'}
        ],
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ]
      },
      dialogTitle: '服务器新增',
      dialogType: 0,
      tagsOptions: [
        {
          value: '测试服务器',
          label: '测试服务器'
        }
      ],
      selectTags: ''
    }
  },
  methods: {
    async getList() {
      this.tableLoading = true
      this.expandRowKeys = []
      let res = await this.$http.post('/api/serverInfo/list', this.listQuery)
      this.tableData = res.data
      this.tableLoading = false
    },
    resetList() {
      this.listQuery.host = ''
      this.getList()
    },
    serverAdd() {
      this.dialogVisible = true
    },
    serverDetail(index, row) {

    },
    serverUpdate(index, row) {
      this.addServerInfo = row
      this.dialogTitle = '服务器编辑'
      this.dialogType = 1
      if (row.tags != null && row.tags != '') {
        this.selectTags = row.tags.split(",")
      } else {
        this.selectTags = []
      }
      this.dialogVisible = true
    },
    submitUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          this.$confirm('确定修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.updateServerInfoMethod()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消修改'
            });
          });
        }
      })
    },
    async updateServerInfoMethod() {
      this.addServerInfo.tags = this.selectTags.join(',')
      let res = await  this.$http.post('/api/serverInfo/update', this.addServerInfo)
      if (res.code == 0) {
        this.$message({
          type: 'success',
          message: res.message
        });
        this.dialogVisible = false
        await this.getList()
      } else {
        this.$message({
          message: res.message,
          type: 'error'
        })
      }
    },
    async addServerInfoMethod() {
      let res = await this.$http.post('/api/serverInfo/add', this.addServerInfo)
      if (res.code == 0) {
        this.$message({
          type: 'success',
          message: res.message
        });
        this.dialogVisible = false
        await this.getList()
      } else {
        this.$message({
          message: res.message,
          type: 'error'
        })
      }
    },
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          this.$confirm('确定添加?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addServerInfoMethod()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加'
            });
          });
        }
      })
    },
    serverDelete(index, row) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteServerInfoMethod(row.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async deleteServerInfoMethod(id) {
      let res = await this.$http.delete('/api/serverInfo/deleteById?id=' + id)
      if (res.code == 0) {
        this.$message({
          type: 'success',
          message: res.message
        });
        this.dialogVisible = false
        await this.getList()
      } else {
        this.$message({
          message: res.message,
          type: 'error'
        })
      }
    },
    handleCommand(command, index, row) {
      console.log(command)
      console.log(index)
      console.log(row)
      // this.openWindow(command, row)
      let req = {
        command: command,
        id: row.id,
        host: row.host
      }
      ipcRenderer.send('newwindow', req)
    },
    openWindow(command, row) {
      let id = row.id
      const {href} = this.$router.resolve({
        name: "ServerLogs",
        query: {
          command: command,
          serverId: row.id
        }
      })
      const config = '' +
          'width=1024, height=700,' +
          'top=0, left=0,' +
          'titlebar=yes, menubar=yes,' +
          'scrollbars=yes,' +
          'resizable=yes,' +
          'status=yes,' +
          'toolbar=yes,' +
          'location=yes'
      window.open(href, '_blank', config)
    }
  },
  created: function(){
    this.getList()
  }
}
</script>

<style>
.serverAdd {
  float: right;
}
.addButtonItem {
  text-align: right;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
</style>

